package com.rzico.sbl.ui.manager

import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupCupboardCodeBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CupboardCodeData
import com.rzico.sbl.model.PickGoodsData
import com.rzico.sbl.other.showCupboardItemDialog
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.TimeHelper
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.BaseDialog
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.setCompoundDrawable
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.labelview.LabelView
import com.xinnuo.slimadapter.SlimAdapter

class PickupCupboardCodeActivity : BaseActivity(R.layout.activity_pickup_cupboard_code) {

    private val mBinding by lazy { ActivityPickupCupboardCodeBinding.bind(getRootView()) }

    private var mPickupId = ""
    private var mCupboardId = ""
    private var isEditMode = false

    private var mDialog: BaseDialog? = null
    private var mDialogName: TextView? = null
    private var mDialogPrice: TextView? = null
    private var mDialogList: ArrayList<String>? = null

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        initTitle(title = "自提柜管理", name = "编辑")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关自提柜门信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            getViewModel()
                                .delay(1500) { getData() }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration())

                    mAdapter = SlimAdapter.creator()
                        .register<CupboardCodeData>(R.layout.item_pickup_cupboard_code) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_code_num, "柜门编号-${bean.no}")
                                text(R.id.item_code_name, bean.productName.orEmpty("无"))
                                text(
                                    R.id.item_code_period,
                                    conditionIf(
                                        bean.period.isNullOrEmpty(),
                                        "",
                                        "${bean.period}个月"
                                    )
                                )
                                text(R.id.item_code_time, bean.replenishDate.getTimeString())
                                text(
                                    R.id.item_code_change,
                                    conditionIf(
                                        bean.stockId.isNullOrEmpty(),
                                        "添加商品",
                                        "更换商品"
                                    )
                                )

                                visibility(
                                    R.id.item_code_back,
                                    visibleValue { bean.stock.intValue > 0 }
                                )

                                visibility(
                                    R.id.item_code_fill,
                                    visibleValue { bean.stock.intValue == 0 }
                                )

                                with<ImageView>(R.id.item_code_check) {
                                    it.isVisible = isEditMode
                                    it.setImageResource(
                                        conditionIf(
                                            bean.check,
                                            R.mipmap.login_yes_orange,
                                            R.mipmap.login_no
                                        )
                                    )
                                }

                                with<ImageView>(R.id.item_code_img) {
                                    bean.thumbnail
                                        .isNullOrEmpty()
                                        .conditionElse(
                                            actionTrue = {
                                                it.setImageResource(R.mipmap.icon_manager30)
                                            },
                                            actionFalse = {
                                                it.loadImage(bean.thumbnail)
                                            }
                                        )
                                }

                                with<LabelView>(R.id.item_code_status) {
                                    it.text = "待补货"
                                    it.bgColor = getColorEx(R.color.red)
                                    it.isVisible = bean.stock.intValue == 0

                                    (bean.stock.intValue > 0
                                            && bean.period.intValue > 0
                                            && !bean.replenishDate.isNullOrEmpty())
                                        .condition {
                                            val periodDate = TimeHelper
                                                .getInstance()
                                                .run {
                                                    stringToLong(
                                                        getAfterMonth(
                                                            bean.replenishDate.getTimeString(),
                                                            bean.period.intValue,
                                                            "yyyy-MM-dd HH:mm:ss"
                                                        )
                                                    )
                                                }

                                            (System.currentTimeMillis() > periodDate)
                                                .condition {
                                                    it.isVisible = true
                                                    it.text = "已过期"
                                                    it.bgColor = getColorEx(R.color.orange)
                                                }
                                        }
                                }

                                clicked(R.id.item_code_check) {
                                    bean.check = !bean.check
                                    notifyItemChanged(index)

                                    checkListener()
                                }

                                clicked(R.id.item_code_open) {
                                    showHintDialog(
                                        hint = "确定要开启${bean.no}号柜门吗？",
                                        onSure = {
                                            openCupboard(bean.no)
                                        }
                                    )
                                }

                                clicked(R.id.item_code_change) {
                                    bean.stockId
                                        .isNullOrEmpty()
                                        .conditionElse(
                                            actionTrue = {
                                                startActivityEx<PickupGoodsActivity>(
                                                    "pickId" to mPickupId,
                                                    "mode" to "single",
                                                    "index" to index
                                                )
                                            },
                                            actionFalse = {
                                                showCupboard(
                                                    cupboardNo = bean.no,
                                                    cupboardStock = bean.stock,
                                                    cupboardStockId = bean.stockId.orEmpty(),
                                                    cupboardUrl = bean.thumbnail.orEmpty(),
                                                    cupboardName = bean.productName.orEmpty(),
                                                    cupboardPrice = bean.price.orEmpty(),
                                                    cupboardPeriod = bean.period.orEmpty(),
                                                    index = index
                                                )
                                            }
                                        )
                                }

                                clicked(R.id.item_code_back) {
                                    bean.stockId
                                        .notEmpty {
                                            showHintDialog(
                                                hint = "确定要回收${bean.no}号柜门商品吗？",
                                                onSure = {
                                                    editCupboard(
                                                        codeNo = bean.no,
                                                        codeNum = "0",
                                                        goodsId = bean.stockId.orEmpty(),
                                                        goodsUrl = bean.thumbnail.orEmpty(),
                                                        goodsName = bean.productName.orEmpty(),
                                                        goodsPeriod = bean.period.orEmpty(),
                                                        index = index
                                                    )
                                                }
                                            )
                                        }
                                }

                                clicked(R.id.item_code_fill) {
                                    bean.stockId
                                        .isNullOrEmpty()
                                        .conditionElse(
                                            actionTrue = { showToast("请先添加要补货的商品") },
                                            actionFalse = {
                                                showHintDialog(
                                                    hint = "确定要补货${bean.no}号柜门商品吗？",
                                                    onSure = {
                                                        fillCupboard(bean.no, index)
                                                    }
                                                )
                                            }
                                        )
                                }
                            }
                        }
                        .attachTo(view)
                }
            }

        tvRight?.oneClick { view ->
            view as TextView

            isEditMode = !isEditMode
            view.text = conditionIf(
                isEditMode,
                "取消",
                "编辑"
            )

            mBinding.codeBottom.isVisible = isEditMode

            if (isEditMode) {
                mList.forEach {
                    it as CupboardCodeData
                    it.check = false
                }

                checkListener()
            }

            mAdapter.notifyDataSetChanged()
        }
    }

    override fun initListener() {
        mPickupId = intent.getExtra("pickId")
        mCupboardId = intent.getExtra("cupboardId")

        mBinding.apply {
            codeAll.setCompoundDrawable(
                leftSize = 16f,
                leftDrawable = R.drawable.address_default_selector
            )

            codeOpen.oneClick {
                mList.none { (it as CupboardCodeData).check }
                    .condition {
                        showToast("请选择要开启的柜门")
                        return@oneClick
                    }

                showHintDialog(
                    hint = "确定要执行一键开门吗？",
                    onSure = {
                        openCupboard(
                            mList
                                .filter { (it as CupboardCodeData).check }
                                .joinToString(",") {
                                    (it as CupboardCodeData).no
                                }
                        )
                    }
                )
            }

            codeFill.oneClick {
                mList.none { (it as CupboardCodeData).check }
                    .condition {
                        showToast("请选择要补货的柜门")
                        return@oneClick
                    }

                mList.filter {
                    it as CupboardCodeData
                    it.check && it.stockId.isNullOrEmpty()
                }.notEmpty {
                    val numbers = joinToString("、") {
                        it as CupboardCodeData
                        it.no
                    }
                    showToast("柜门编号${numbers}未设置商品，请先添加补货商品")
                    return@oneClick
                }

                mList.filter { (it as CupboardCodeData).check }
                    .apply {
                        val numbers = joinToString(",") {
                            it as CupboardCodeData
                            it.no
                        }

                        fillCupboard(numbers)
                    }
            }
        }

        observe<PickGoodsData>("cupboardCode") { data ->
            val item = mList[data.position] as CupboardCodeData

            (mDialog == null)
                .conditionElse(
                    actionTrue = {
                        showCupboard(
                            cupboardNo = item.no,
                            cupboardStock = item.stock,
                            cupboardStockId = data.id,
                            cupboardUrl = data.thumbnail.orEmpty(),
                            cupboardName = data.name,
                            cupboardPrice = data.price,
                            cupboardPeriod = item.period.orEmpty(),
                            index = data.position
                        )
                    },
                    actionFalse = {
                        mDialogName?.text = data.name
                        mDialogPrice?.text = data.price
                        mDialogList?.let {
                            it[2] = data.id
                            it[3] = data.thumbnail.orEmpty()
                            it[4] = data.name
                        }
                    }
                )
        }
    }

    private fun showCupboard(
        cupboardNo: String,
        cupboardStock: String,
        cupboardStockId: String,
        cupboardUrl: String,
        cupboardName: String,
        cupboardPrice: String,
        cupboardPeriod: String,
        index: Int
    ) {
        mDialog =
            showCupboardItemDialog(
                item = CupboardCodeData().apply {
                    no = cupboardNo
                    stock = cupboardStock
                    stockId = cupboardStockId
                    thumbnail = cupboardUrl
                    productName = cupboardName
                    price = cupboardPrice
                    period = cupboardPeriod
                },
                index = index,
                isForced = true,
                onSelect = { nameView, priceView, list ->
                    mDialogName = nameView
                    mDialogPrice = priceView
                    mDialogList = list

                    startActivityEx<PickupGoodsActivity>(
                        "pickId" to mPickupId,
                        "mode" to "single",
                        "index" to index
                    )
                },
                onSure = {
                    editCupboard(
                        codeNo = it[0],
                        codeNum = it[1],
                        goodsId = it[2],
                        goodsUrl = it[3],
                        goodsName = it[4],
                        goodsPeriod = it[5],
                        index = it[6].intValue
                    )
                },
                onDismiss = {
                    mDialogList = null
                    mDialogPrice = null
                    mDialogName = null
                    mDialog = null
                }
            )
    }

    /**
     * 自提柜开门
     */
    private fun openCupboard(numbers: String) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngCupCellOpe,
                params = arrayOf(
                    "cabinetId" to mCupboardId,
                    "nos" to numbers
                ),
                onSuccess = {
                    showToast("开门指令发送成功！")
                }
            )
    }

    /**
     * 柜门补货
     */
    private fun fillCupboard(numbers: String, index: Int = -1) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngCupCellFil,
                params = arrayOf(
                    "cabinetId" to mCupboardId,
                    "nos" to numbers
                ),
                onSuccess = {
                    showToast("柜门补货成功！")

                    (index > -1)
                        .conditionElse(
                            actionTrue = {
                                mList[index].apply {
                                    this as CupboardCodeData

                                    stock = "1"
                                    replenishDate = System.currentTimeMillis().toString()
                                }

                                mAdapter.notifyItemChanged(index)
                            },
                            actionFalse = {
                                isEditMode = false

                                tvRight?.text = "编辑"
                                mBinding.codeBottom.isVisible = isEditMode

                                updateList()
                            }
                        )

                    // 刷新自提柜列表
                    LiveEventBus
                        .get("cupboardList")
                        .post("refresh")
                }
            )
    }

    /**
     * 柜门商品库存管理
     */
    private fun editCupboard(
        codeNo: String,
        codeNum: String,
        goodsId: String,
        goodsUrl: String,
        goodsName: String,
        goodsPeriod: String,
        index: Int
    ) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngCupCellSav,
                params = arrayOf(
                    "cabinetId" to mCupboardId,
                    "stockId" to goodsId,
                    "no" to codeNo,
                    "stock" to codeNum,
                    "period" to goodsPeriod
                ),
                onSuccess = {
                    showToast("操作成功！")

                    (mList[index] as CupboardCodeData)
                        .apply {
                            stockId = goodsId
                            thumbnail = goodsUrl
                            productName = goodsName
                            stock = codeNum
                            period = goodsPeriod
                            replenishDate = conditionIf(
                                stock.intValue > 0,
                                System.currentTimeMillis().toString(),
                                ""
                            )
                        }
                    mAdapter.notifyItemChanged(index)

                    // 刷新自提柜列表
                    LiveEventBus
                        .get("cupboardList")
                        .post("refresh")
                }
            )
    }

    /**
     * 自提柜列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .cupboardItem(
                cupboardId = mCupboardId,
                onSuccess = {
                    mList.apply {
                        clear()
                        addItems(it.filter { it.enable })
                    }

                    mAdapter.setDataList(mList)

                    isEditMode.condition { checkListener() }
                },
                onFinally = {
                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData()
    }

    private fun checkListener() {
        mBinding.apply {
            codeAll
                .apply {
                    setOnCheckedChangeListener(null)
                    isChecked =
                        mList.isNotEmpty() && mList.none { !(it as CupboardCodeData).check }
                    setOnCheckedChangeListener(this@PickupCupboardCodeActivity)
                }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        mList.forEach { (it as CupboardCodeData).check = isChecked }
        mAdapter.notifyDataSetChanged()

        checkListener()
    }

}